package com.mission.game.creategame;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.mission.game.R;
import com.mission.game.utils.BarcodeTask;
import com.mission.game.utils.Task;

public class CreateBarcodeTask extends CreateAbstractTask {

	private EditText _scanResult;
	private static final String GENERATE_URI = "http://chart.apis.google.com/chart?cht=qr&chs=350x350&chld=L&choe=UTF-8&chl=";
	private static final String DEBUG_TAG = "Barcode Creation";

	@Override
	protected int getScoreInput() {
		return R.id.barcode_score_input;
	}

	@Override
	protected Task newSpecificTask() {
		return new BarcodeTask();
	}

	@Override
	protected int getDescriptionInput() {
		return R.id.barcode_description_input;
	}

	@Override
	protected int getNameInput() {
		return R.id.barcodetask_name_input;
	}

	@Override
	protected int getContentView() {
		return R.layout.create_barcode_task;
	}

	@Override
	protected void specificBackToMissionClicked(View v) {
		if (_scanResult != null)
			((BarcodeTask) _task).setBarcodeContents(_scanResult.getText()
					.toString());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void setFields() {
		super.setFields();
		_scanResult = (EditText) findViewById(R.id.barcode_input);
		_scanResult.setText(((BarcodeTask) _task).getBarcodeContents());
	}

	public void onScanBarcodeClicked(View v) {
		IntentIntegrator integrator = new IntentIntegrator(this);
		integrator.initiateScan();
	}

	public void onGenerateResultClicked(View v) {
		if (_scanResult == null) {
			_scanResult = (EditText) findViewById(R.id.barcode_input);
		}
		String scanResultText = "";
		if (_scanResult.getText() != null) {
			scanResultText = _scanResult.getText().toString();
		}
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			new DownloadWebpagePicture().execute(scanResultText);
		} else {
			Toast.makeText(getApplicationContext(),
					"No network connection available.", Toast.LENGTH_LONG)
					.show();
		}
	}

	private class DownloadWebpagePicture extends
			AsyncTask<String, Integer, Drawable> {
		@Override
		protected Drawable doInBackground(String... urls) {
			// params comes from the execute() call: params[0] is the url.
			try {
				URL url = new URL(GENERATE_URI + urls[0]);
				return downloadUrl(url);
			} catch (MalformedURLException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}

		protected void onPostExecute(Drawable drawable) {
			ImageView imageView = new ImageView(getApplicationContext());
			if (drawable != null) {
				imageView.setImageDrawable(drawable);
				loadPhoto(imageView);
			}
			;
		}
	}

	// Given a URL, establishes an HttpUrlConnection and retrieves
	// the web page content as a InputStream, which it returns as
	// a drawable.
	private Drawable downloadUrl(URL url) throws IOException {
		InputStream is = null;

		try {
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(10000 /* milliseconds */);
			conn.setConnectTimeout(15000 /* milliseconds */);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			// Starts the query
			conn.connect();
			int response = conn.getResponseCode();
			Log.d(DEBUG_TAG, "The response is: " + response);
			is = conn.getInputStream();

			// Convert the InputStream into a string
			Drawable d = Drawable.createFromStream(is, "src name");
			return d;

			// Makes sure that the InputStream is closed after the app is
			// finished using it.
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

	private void loadPhoto(ImageView imageView) {

		AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.popup_image_dialog,
				(ViewGroup) findViewById(R.id.popup_image));
		ImageView image = (ImageView) layout.findViewById(R.id.popup_image);
		image.setImageDrawable(imageView.getDrawable());
		imageDialog.setView(layout);
		imageDialog.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		imageDialog.create();
		imageDialog.show();
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		IntentResult scanResult = IntentIntegrator.parseActivityResult(
				requestCode, resultCode, intent);
		if (scanResult != null) {
			if (_scanResult == null) {
				_scanResult = (EditText) findViewById(R.id.barcode_input);
			}
			// Put scan result into result EditText view
			_scanResult.setText(scanResult.getContents());
		}
		// else continue with any other code you need in the method
	}
}
